package lesson02;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {

    // 定义数据库连接信息
    static String url;
    static String username;
    static String password;
    static Connection connection;
    static Statement statement;

    static {
        try {
            InputStream resource = JDBCUtils.class.getClassLoader().getResourceAsStream("lesson02/application.properties");
            Properties properties = new Properties();
            properties.load(resource);
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            // 建立数据库连接
            connection = DriverManager.getConnection(url, username, password);
            // 创建 Statement 对象
            statement = connection.createStatement();
        } catch (IOException | SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询数据
     * @param sql 查询语句
     * @return
     * @throws SQLException
     */
    public static ResultSet queryData(String sql) throws SQLException {
        return statement.executeQuery(sql);
    }


    /**
     * 操作数据库
     * @param sql 更新 删除语句
     * @return
     * @throws SQLException
     */
    public static int operateData(String sql) throws SQLException {
        return statement.executeUpdate(sql);
    }

    /**
     * 释放连接
     * @param resultSet
     */
    public static void release(ResultSet resultSet){
        try {
            // 关闭连接
            if (resultSet != null) {
                resultSet.close();
            }
            if (resultSet != null) {
                statement.close();
            }
            if (resultSet != null) {
                connection.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
